package com.dibang.app.mvp.abs;

import android.content.Context;
import android.support.annotation.CallSuper;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by wxl on 2019/6/21.
 *
 */

public abstract class AbsControl<V, P, M, Pro extends BaseProvider<V, P, M>> implements MvpProvider<V, P, M> {

    private Pro pro;

    protected View rootView;

    private Context context;

    public AbsControl(@NonNull View targetView) {
        rootView = targetView;
        context = targetView.getContext();
        pro = (Pro) getProvider();
        if (pro != null) {
            pro.injectProvider(this);
        }
        ((BaseView) getView()).injectControl(this);
    }



    /**
     * 实现默认获取Mvp提供者的方式
     *
     * @return
     * @hide
     */
    @Override
    public BaseProvider<V, P, M> getProvider() {
        return BeanFactory.getInstance(findProClass());
    }


    /**
     * 找到pro
     * @return
     */
    private Class<Pro> findProClass() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<Pro>) params[3];
    }

    /**
     * 获取v层
     *
     * @return
     */
    public V getView() {
        return pro.getView();
    }


    /**
     * 获取targetView绑定的上下文
     *
     * @return
     */
    public Context getContext() {
        return context;
    }

    @ColorInt
    public final int getResColor(@ColorRes int id) {
        return ContextCompat.getColor(getContext(),id);
    }


    /**
     * 释放
     */
    @CallSuper
    public void onDestroy() {
        BeanFactory.remove(findProClass());
        if (pro != null) {
            pro.onDestroy();
        }
        context = null;
        rootView = null;
    }

}
